--require "MainScene"

JLRMLayer={}
JLRMLayerFunc={}
JLRMLayerFunc.__index = JLRMLayerFunc
setmetatable(JLRMLayer, JLRMLayerFunc)

JLRMLayer.NodeID = {ArmyTable=1001, ZhenXingBK=1002, ZhenXingMenu=1003, ZhenXingName=1010, ZhenXingDesc=1011}
--local HeroItem1ID = {ImgBK=2001, TongShuai=2002, ZhanShu=2003, BaoPo=2004, JueZhao=2005, Name=2006, Button=3001}
local HeroItem1ID = {ImgBK=1001, Name=1002, Level=1003, BingZhong=1004, JueZhao=1005, IsUpImg=1006}


JLRMLayerFunc.getNode = function()
  local l = {}
  setmetatable(l, JLRMLayerFunc)
  l.node = CCBReader:load("BuZhenLayer.ccbi")
  l.node:registerScriptTouchHandler(JLRMLayerFunc.onTouchLayer, false, 0, false)
  l.node:setTouchEnabled(true)
  JLRMLayer.instance = l
  print("JLRMLayer.getNode", l.node)
  l:init() 
  --zxLayer:setPosition(ccp(480,320))
  return l 
end

JLRMLayerFunc.getScene = function(self)
  local sc = CCScene:create()
  sc:addChild(JLRMLayer:getNode().node)  
  print("JLRMLayer.getScene", sc)
  return sc
end

JLRMLayerFunc.init = function(self)
 setObjectExtTable(self.node:getChildByTag(1020), self)
 if JLRMLayer.currentZhenXingID==nil then
    print("JLRMLayerFunc.init currentZhenXingID nil")
    JLRMLayer.currentZhenXingID = 9
  end
  print("JLRMLayerFunc.init", JLRMLayer.currentZhenXingID)
  local menu = self.node:getChildByTag(JLRMLayer.NodeID.ZhenXingMenu)
  self.radioMenu = RadioMenu:create(menu, "menuItemChanged", self)
  self.radioMenu:setMenuState(JLRMLayer.currentZhenXingID-9)

  for i=9,14 do
    local zxConfig = UserData.config.models.Technology[i]
    local lb = self.node:getChildByTag(2000+i-8)
    local techLevel = UserData.userinfo.host.store.tech[tostring(i)]
    if techLevel==nil then techLevel=0;end  
    TypeCast(lb, "CCLabelTTF"):setString(string.format("%s %d级", zxConfig.name, techLevel))
  end

  local defaultFormation =UserData.userinfo.host.defaultFormation
  self.gouSprite = CCSprite:create("gou002.png")
  local x,y = self.node:getChildByTag(2000+defaultFormation-8):getPosition()
  self.gouSprite:setPosition(ccp(x+160, y))
  self.node:addChild(self.gouSprite)
end

JLRMLayerFunc.resetLayer = function(self)
  if self.zxLayer~=nil then
    self.node:removeChild(self.zxLayer, true)
  end
  self.zxLayer = self:createZhenXingLayer(JLRMLayer.currentZhenXingID)
  self.node:addChild(self.zxLayer)

  if self.heroTable~=nil then
    self.node:removeChild(self.heroTable, true)
  end
  self.heroTable = self:createArmyTable()
  self.node:addChild(self.heroTable)
end

JLRMLayerFunc.createZhenXingLayer = function(self, zxid)
  local LockSpriteID = 1121
  local items = {}
  local lockSprites = {}
  local l = CCLayer:create()
  self.zx = {}
  self.zx[1] = 0
  self.zxid = zxid
  
  local zxConfig = UserData.config.models.Technology[zxid]
  local lb = self.node:getChildByTag(JLRMLayer.NodeID.ZhenXingName)  
  TypeCast(lb, "CCLabelTTF"):setString(zxConfig.name)
  lb = self.node:getChildByTag(JLRMLayer.NodeID.ZhenXingDesc)  
  TypeCast(lb, "CCLabelTTF"):setString(zxConfig.desc)

  for i=0,8 do
    local x = (2-math.floor(i/3))*118 - 2*118/2
    local y = (2-i%3)*118 - 2*118/2
    --print(x,y)
    local sp = CCSprite:create("headbk.png")
    sp:setPosition(ccp(x,y))
    l:addChild(sp)
    items[i+1] = sp
  
    sp = CCSprite:create("lockbk.png")
    sp:setPosition(ccp(x,y))
    l:addChild(sp)
    lockSprites[i+1] = sp
    sp:setTag(LockSpriteID)

    self.zx[i+2] = -1 
  end
  local bk = self.node:getChildByTag(JLRMLayer.NodeID.ZhenXingBK)
  local x,y = bk:getPosition()
  l:setPosition(ccp(x, y-50))
  self.heroPanels = items 

  local zxInfo = UserData.userinfo.host.formations[tostring(zxid)]
  --if zxInfo==nil then
  --  return l
  --end
 
  --local count = zxInfo[1]
  local techLevel = UserData.userinfo.host.store.tech[tostring(zxid)]
  local formation = UserData.config.models.Technology[zxid].formation
  print("JLRMLayerFunc.createZhenXingLayer", zxid, UserData.config.models.Technology[zxid])
  print("JLRMLayerFunc.createZhenXingLayer", cjson.encode(formation))
   
    for i=1,table.maxn(formation) do
      local requireLevel = UserData.config.models.Technology[zxid][string.format("open%dLevel", i)]
      print("JLRMLayerFunc.createZhenXingLayer##### ", i, requireLevel, zxInfo, techLevel)
      if techLevel~=nil and 
          ((i<=2 and techLevel>0) or (i>2 and requireLevel<=techLevel)) then
        local pos = formation[i]
        print(i, pos)
        local sp = lockSprites[pos] 
        local x, y = sp:getPosition()
        l:removeChild(sp, true)
        self.zx[pos+1] = 0 
        local armyid = 0 
        if zxInfo~=nil then armyid=zxInfo[pos+1]; end
        if armyid~=0 then
          self.zx[pos+1] = armyid
          --local imgName = string.format("%d.png",armyid%40)
          local info = UserData.config.models.General[tonumber(armyid)]
          local imgName = string.format("%s_100.png",info.asset)
          local button = CCButton:createWithFileName("onHeroButton", imgName, imgName, imgName, "")
          button:setTag(pos)
          setObjectExtTable(button, self)
          button:setPosition(ccp(x, y))
          button:setTouchEndOnly(false)
          l:addChild(button)
        end
      else
        local lb = nil
        if i<=2 then
          lb = CCLabelTTF:create(string.format("%s\n%d级\n开启", zxConfig.name, 1), "Helvetica", 24)
        else
          local requireLevel = UserData.config.models.Technology[zxid][string.format("open%dLevel", i)]
          lb = CCLabelTTF:create(string.format("%s\n%d级\n开启", zxConfig.name, requireLevel), "Helvetica", 24)
        end 
        local pos = formation[i]
        local sp = lockSprites[pos]
        local x, y = sp:getPosition()
        print("JLRMLayerFunc.createZhenXingLayer#####$ ", i, pos)
        l:addChild(lb)
        lb:setPosition(ccp(x,y))
      end 
  end
  return l
end

JLRMLayerFunc.createArmyTable = function(self)
  local armys = UserData.userinfo.host.armyGroups
  local tmp = {}
  for k,v in pairs(armys) do
    if v.s==1 then
      --tmp[#tmp+1] = {index=k, v=v}--[k] = v
      tmp[k] = v
    end
  end
  
  local sortedArmys = {}
  local zxInfo = UserData.userinfo.host.formations[tostring(JLRMLayer.currentZhenXingID)]
  if zxInfo~=nil then
    for k,v in pairs(zxInfo) do
      if k>1 and v>0 then
        sortedArmys[#sortedArmys+1] = {armyID=v, v=tmp[tostring(v)], up=1}
        tmp[tostring(v)] = nil
      end 
    end
  end
  for k, v in pairs(tmp) do
    sortedArmys[#sortedArmys+1] = {armyID=tonumber(k), v=v, up=0}
  end
  
  local sortFunc = function(a, b)
    if a.up>b.up then
      return true
    elseif a.up<b.up then
      return false
    else
      return a.v.l>b.v.l
    end 
  end
  table.sort(sortedArmys, sortFunc)
  for k,v in ipairs(sortedArmys) do
    print(k, v.armyID, v.up)
  end  

  local items = CCArray:create()
  for i=1,#sortedArmys do
  --for k,v in pairs(armys) do
    local k=sortedArmys[#sortedArmys+1-i].armyID
    local v=UserData.userinfo.host.armyGroups[tostring(k)]
    print("initArmygroupTable", k, v)
    local item = CCBReader:load("HeroItem1.ccbi")
    local info = UserData.config.models.General[tonumber(k)]
    --local sp = CCSprite:create(string.format("%s.png", info.asset))
    --local imgName = string.format("%d.png",k%40)
    local imgName = string.format("%s_100.png",info.asset)
    local button = CCButton:createWithFileName("onHeroButton", imgName, imgName, imgName, "")
    local imgBK = item:getChildByTag(HeroItem1ID.ImgBK)
    button:setPosition(imgBK:getPosition())
    button:setTag(tonumber(k))
    button:setTouchEndOnly(false)
    setObjectExtTable(button, self)
    item:addChild(button)
    local upImg = CCSprite:create("chuzhanimg.png")--item:getChildByTag(HeroItem1ID.IsUpImg)
    upImg:setPosition(ccp(100,100))
    if sortedArmys[#sortedArmys+1-i].up==1 then    
      item:addChild(upImg)
      print("add up img") 
    end 
    local lb = TypeCast(item:getChildByTag(HeroItem1ID.Name), "CCLabelTTF")
    lb:setString(info.name)
    lb:setColor(Equip.EquipColor[info.quality])
    --[[
    if info.quality=="green" then
      lb:setColor(ccc3(0,255,0))
    elseif info.quality=="blue" then
      lb:setColor(ccc3(0,0,255))
    else
      lb:setColor(ccc3(255,255,255))
    end]]
    lb = item:getChildByTag(HeroItem1ID.BingZhong)
    TypeCast(lb, "CCLabelTTF"):setString(info.desc)
    lb = item:getChildByTag(HeroItem1ID.Level)
    TypeCast(lb, "CCLabelTTF"):setString(string.format("Lv%d", v.l))

    item:setContentSize(CCSizeMake(250,127))
    items:addObject(item)
  end
  
  local tableBK = self.node:getChildByTag(JLRMLayer.NodeID.ArmyTable)
  local tableview = CCTableView:create(1, CCSizeMake(250, 420), items)
  --local x, y = ActionUtil.leftBottomPoint(tableBK)
  tableview:setPosition(44, 44)
  --self.node:addChild(tableview)
  --self.heroTable = tableview
  return tableview
end

JLRMLayerFunc.onChangeArmy = function(self, node, event)
  print("JLRMLayerFunc.onChangeArmy")
end

JLRMLayerFunc.onHeroButton = function(self, node, event)
  
  self.movingArmyID = 0
  self.posBegin = -1
  if node:getParent()==self.zxLayer then
    self.posBegin = node:getTag()
    self.movingArmyID = self.zx[self.posBegin+1]
  else
    self.movingArmyID = node:getTag()
  end

  if event==CCControlEventTouchDragExit then
  --print("JLRMLayerFunc.onHeroButton drag exit", event, node:getTag())
    print("JLRMLayerFunc.onHeroButton touch zx", self.posBegin, self.movingArmyID)
    local info = UserData.config.models.General[tonumber(self.movingArmyID)]
    local imgName = string.format("%s_100.png",info.asset) 
    --local imgName = string.format("%d.png", self.movingArmyID%40)
    local sp = CCSprite:create(imgName)
    
    local pos = node:getPositionLua()
    pos = node:getParent():convertToWorldSpace(pos)
    pos = self.node:convertToNodeSpace(pos)
    sp:setPosition(pos)
    self.node:addChild(sp)
    self.movesp = sp
  --self.movingArmyID = node:getTag()
  else
    print("JLRMLayerFunc.onHeroButton touched ", event, node:getTag()) 
    --if self.curTip~=nil then
    --  self.node:removeChild(self.curTip, true)
    --end
    local hd = HeroData:create(self.movingArmyID)
    local tip = hd:createTip()
    --tip:setPosition(ccp(480, ))
    --setTouchEnabledAll(self.node, false)
    
    self.curTip = tip
    self.node:addChild(self.curTip)
    self.curTip:registerScriptTouchHandler(JLRMLayerFunc.onTouchTipLayer, false, -1111, true)
    self.curTip:setTouchEnabled(true)
  end
end

JLRMLayerFunc.onShouLuButton = function(self, node, event)
  print("JLRMLayerFunc.onShouLuButton")
end
JLRMLayerFunc.onTouchTipLayer = function(event, x, y)
  if event==CCTOUCHBEGAN then 
    if JLRMLayer.instance.curTip~=nil then
      print("onTouchTipLayer clear tip")
      JLRMLayer.instance.node:removeChild(JLRMLayer.instance.curTip, true)
      JLRMLayer.instance.curTip = nil
    end
  end
  return true
end
JLRMLayerFunc.onTouchLayer = function(event, x, y)
  print("onTouchLayer", event, x, y)
  if event==CCTOUCHBEGAN then 
    return true 
  elseif event==CCTOUCHMOVED then
    if JLRMLayer.instance.movesp then
      JLRMLayer.instance.movesp:setPosition(x,y)
    end
  elseif event==CCTOUCHENDED then 
    if JLRMLayer.instance.movesp then
      JLRMLayer.instance:checkMoveIn(x,y)
    end
  end
  return false
end

JLRMLayerFunc.checkMoveIn = function(self, x,y)
  local changed = false
  local tmpzx = {}
  for k, v in pairs(self.zx) do
    if v<0 then tmpzx[k] = 0;else tmpzx[k]=v end
  end
  print("JLRMLayerFunc.checkMoveIn", cjson.encode(tmpzx))

  for i=1,#self.heroPanels do
    local tp = self.zxLayer:convertToNodeSpace(ccp(x,y))
    local rect = ActionUtil.getNodeRect(self.heroPanels[i])
    --print("EquipHeroScene.checkMoveIn ", x, y, tp.x, tp.y, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)
    if rect:containsPoint(tp) then
      print("#########", i)
      if i==self.posBegin then
        print("no changed")
        break
      end
      local t = tmpzx[i+1]
      tmpzx[i+1] = self.movingArmyID
      if self.posBegin > 0 then
        tmpzx[self.posBegin+1] = t 
      end 
      changed = true 
      break
    end
  end
  if changed==false then
    local rect = CCRectMake(44, 44, 250, 420)
    if rect:containsPoint(ccp(x,y)) and self.posBegin>0 then
      print("remove sp")
      if self.posBegin>0 then
        tmpzx[self.posBegin+1] = 0
      end 
      changed = true 
    end 
  end

  if changed==true then
    local c = 0
    for k,v in pairs(tmpzx) do if v>0 then c=c+1;end end 
    tmpzx[1] = c
    print("JLRMLayerFunc.checkMoveIn", cjson.encode(tmpzx))
    NetworkRequest.changeZhenXing(self.zxid, tmpzx, "onChangeZhenXingComplete", self)
    self.node:removeChild(self.movesp, true)
    self.movesp = nil
    --setTouchEnabledAll(JunXiaoScene.instance.node, false)
    LoadScene:showLoadingScene()
  else
    self.node:removeChild(self.movesp, true)
    self.movesp=nil 
  end
end

JLRMLayerFunc.onChangeZhenXingComplete = function(self, data)
  print("JLRMLayerFunc.onChangeZhenXingComplete", data)
  --setTouchEnabledAll(JunXiaoScene.instance.node, true)
  LoadScene:removeLoadingScene()
 
  local res = cjson.decode(data)
  if res.ret==0 then
    NetworkRequest.syncData(res)
    showMessage("布阵成功", ccc3(0,255,0))
    self:resetLayer()
  else
    showMessage(res.msg, ccc3(255,255,0))
  end
end

JLRMLayerFunc.menuItemChanged = function(self, oldIndex, newIndex)
  print("JLRMLayerFunc.menuItemChanged", newIndex)
  if self.zxLayer~=nil then
    self.node:removeChild(self.zxLayer, true)
  end
  JLRMLayer.currentZhenXingID = 9+newIndex
  --self.zxLayer = self:createZhenXingLayer(9+newIndex)
  --self.node:addChild(self.zxLayer)
  self:resetLayer()
end

JLRMLayerFunc.onQiYongZhenXingButton = function(self, node, event)
  NetworkRequest.qiYongZhenXing(JLRMLayer.currentZhenXingID, "onQiYongZhenXingComplete", self)
  --setTouchEnabledAll(JunXiaoScene.instance.node, false)
  LoadScene:showLoadingScene()
end

JLRMLayerFunc.onQiYongZhenXingComplete = function(self, data)
  --setTouchEnabledAll(JunXiaoScene.instance.node, true)
  LoadScene:removeLoadingScene()
  local res = cjson.decode(data)
  if res.ret==0 then
    NetworkRequest.syncData(res)
    local defaultFormation = JLRMLayer.currentZhenXingID
    UserData.userinfo.host.defaultFormation = defaultFormation
    --self.gouSprite = CCSprite:create("gou002.png")
    local x,y = self.node:getChildByTag(2000+defaultFormation-8):getPosition()
    self.gouSprite:setPosition(ccp(x+160, y))
    showMessage("启用阵法成功", ccc3(0,255,0))
  else
    showMessage(res.msg, ccc3(255,255,0))
  end
end
